package com.lzp.systemopt.camera.view

import android.app.Activity
import android.content.Context
import android.graphics.SurfaceTexture
import android.util.AttributeSet
import android.view.TextureView
import android.view.View
import com.lzp.systemopt.camera.CameraManager
import com.lzp.systemopt.camera.CaptureListener
import com.lzp.systemopt.camera.ICameraManager
import com.utils.LogUtils

/**
 * @description:
 * @author: lxp
 * @date: 2022/1/22 上午10:33
 */
class CameraSurfaceView @kotlin.jvm.JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : TextureView(context, attrs, defStyle) {

    private val TAG = "CameraSurfaceView"

    private var mRatioWidth = 0
    private var mRatioHeight = 0


    private val mCameraManager = CameraManager.getInstance()

    fun initCamera(activity: Activity) {
        mCameraManager.initCamera(activity, this)
    }

    fun setCaptureListener(listener: CaptureListener) {
        mCameraManager.setCaptureListener(listener)
    }

    fun startCapturePicPreView() {
        mCameraManager.startCapturePicPreView()
    }

    fun startCaptureVideoPreview() {
        mCameraManager.startCaptureVideoPreview()
    }

    fun stopCapturePicPreView() {
        mCameraManager.stopCapturePicPreView()
    }

    fun stopCaptureVideoPreview() {
        mCameraManager.stopCaptureVideoPreview()
    }

    fun capturePic() {
        mCameraManager.capturePic()
    }

    fun captureVideo() {
        mCameraManager.captureVideo()
    }

    fun stopCaptureVideo() {
        mCameraManager.stopCaptureVideo()
    }

    fun releaseCamera(reason: String) {
        mCameraManager.releaseCamera(reason)
    }

    fun requestSwitchCamera() {
        mCameraManager.requestSwitchCamera()
    }

    fun setAspectRatio(width: Int, height: Int) {
        if (width < 0 || height < 0) {
            LogUtils.d(TAG, "Size cannot be negative.")
            return
        }
        mRatioWidth = width
        mRatioHeight = height
        requestLayout()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = View.MeasureSpec.getSize(widthMeasureSpec)
        val height = View.MeasureSpec.getSize(heightMeasureSpec)
        if (mRatioWidth == 0 || mRatioHeight == 0) {
            setMeasuredDimension(width, height)
        } else {
            if (width < ((height * mRatioWidth) / mRatioHeight)) {
                setMeasuredDimension(width, (width * mRatioHeight) / mRatioWidth)
            } else {
                setMeasuredDimension((height * mRatioWidth) / mRatioHeight, height)
            }
        }
    }

}